﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using TPOJ.Model;
using TPOJ.BLL;
using System.Web.Caching;
using TPOJ.CacheDependencyFactory;

namespace TPOJ.Web
{
    public static class ForumDataProxy
    {
        private static readonly int forumTimeout = int.Parse(ConfigurationManager.AppSettings["ForumCacheDuration"]);
        private static readonly bool enableCaching = bool.Parse(ConfigurationManager.AppSettings["EnableCaching"]);

        public static IList<ForumMessage> GetForumMessagesByProblemId(int problemId)
        {
            ForumBO forumBO = new ForumBO();

            if (!enableCaching)
                return forumBO.GetForumMessagesByProblemId(problemId);

            string key = "forumMessage_problem" + problemId;

            IList<ForumMessage> data = (IList<ForumMessage>)HttpRuntime.Cache[key];

            if (data == null)
            {
                data = forumBO.GetForumMessagesByProblemId(problemId);

                AggregateCacheDependency aggrCacheDependency = DependencyFacade.GetForumMessageDependency();

                HttpRuntime.Cache.Add(key, data, aggrCacheDependency, DateTime.Now.AddHours(forumTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }
            return data;
        }

        public static ForumMessage GetForumMessage(int id)
        {
            ForumBO forumBO = new ForumBO();

            if (!enableCaching)
                return forumBO.GetForumMessage(id);

            string key = "forumMessage" + id;

            ForumMessage data = (ForumMessage)HttpRuntime.Cache[key];

            if (data == null)
            {
                data = forumBO.GetForumMessage(id);

                AggregateCacheDependency aggrCacheDependency = DependencyFacade.GetForumMessageDependency();

                HttpRuntime.Cache.Add(key, data, aggrCacheDependency, DateTime.Now.AddHours(forumTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }
            return data;
        }
    }
}